// 棋盘8x9，地形：NORMAL, DEN, TRAP, RIVER
const ROWS = 9, COLS = 7;
const terrainMap = [
  ['NORMAL','NORMAL','TRAP','DEN','TRAP','NORMAL','NORMAL'],
  ['NORMAL','NORMAL','NORMAL','TRAP','NORMAL','NORMAL','NORMAL'],
  ['NORMAL','NORMAL','NORMAL','NORMAL','NORMAL','NORMAL','NORMAL'],
  ['NORMAL','RIVER','RIVER','NORMAL','RIVER','RIVER','NORMAL'],
  ['NORMAL','RIVER','RIVER','NORMAL','RIVER','RIVER','NORMAL'],
  ['NORMAL','RIVER','RIVER','NORMAL','RIVER','RIVER','NORMAL'],
  ['NORMAL','NORMAL','NORMAL','NORMAL','NORMAL','NORMAL','NORMAL'],
  ['NORMAL','NORMAL','NORMAL','TRAP','NORMAL','NORMAL','NORMAL'],
  ['NORMAL','NORMAL','TRAP','DEN','TRAP','NORMAL','NORMAL'],
];

const initialPieces = [
  // 玩家1（下）
  { type: 'ELEPHANT', owner: 0, x: 8, y: 0 },
  { type: 'LION', owner: 0, x: 8, y: 6 },
  { type: 'TIGER', owner: 0, x: 7, y: 1 },
  { type: 'LEOPARD', owner: 0, x: 7, y: 5 },
  { type: 'WOLF', owner: 0, x: 7, y: 0 },
  { type: 'DOG', owner: 0, x: 7, y: 6 },
  { type: 'CAT', owner: 0, x: 6, y: 2 },
  { type: 'RAT', owner: 0, x: 6, y: 4 },
  // 玩家2（上）
  { type: 'ELEPHANT', owner: 1, x: 0, y: 0 },
  { type: 'LION', owner: 1, x: 0, y: 6 },
  { type: 'TIGER', owner: 1, x: 1, y: 1 },
  { type: 'LEOPARD', owner: 1, x: 1, y: 5 },
  { type: 'WOLF', owner: 1, x: 1, y: 0 },
  { type: 'DOG', owner: 1, x: 1, y: 6 },
  { type: 'CAT', owner: 1, x: 2, y: 2 },
  { type: 'RAT', owner: 1, x: 2, y: 4 },
];

const pieceRank = {
  'ELEPHANT': 8,
  'LION': 7,
  'TIGER': 6,
  'LEOPARD': 5,
  'WOLF': 4,
  'DOG': 3,
  'CAT': 2,
  'RAT': 1,
};

export function getInitialBoard() {
  const board = Array.from({ length: ROWS }, (_, i) =>
    Array.from({ length: COLS }, (_, j) => ({ terrain: terrainMap[i][j], piece: null }))
  );
  initialPieces.forEach(p => {
    board[p.x][p.y].piece = { type: p.type, owner: p.owner, hasEnteredTrap: false };
  });
  return board;
}

export function getNextPlayer(current) {
  return 1 - current;
}

export function cloneBoard(board) {
  return board.map(row => row.map(cell => ({
    terrain: cell.terrain,
    piece: cell.piece ? { ...cell.piece } : null
  })));
}

export function isValidMove(board, from, to, currentPlayer) {
  const piece = board[from.x][from.y].piece;
  if (!piece || piece.owner !== currentPlayer) return false;
  const dx = Math.abs(to.x - from.x), dy = Math.abs(to.y - from.y);
  const dest = board[to.x][to.y];
  // 跳河规则（狮/虎）
  if ((piece.type === 'LION' || piece.type === 'TIGER') && isJumpRiver(board, from, to)) {
    if (!canJumpRiver(board, from, to)) return false;
    if (dest.piece && dest.piece.owner === currentPlayer) return false;
    if (dest.terrain === 'DEN' && ((currentPlayer === 0 && to.x === 8) || (currentPlayer === 1 && to.x === 0))) return false;
    if (dest.piece && !canCapture(board, from, to)) return false;
    return true;
  }
  // 普通走法
  if (dx + dy !== 1) return false;
  if (dest.piece && dest.piece.owner === currentPlayer) return false;
  // 不能进己方兽穴
  if (dest.terrain === 'DEN' && ((currentPlayer === 0 && to.x === 8) || (currentPlayer === 1 && to.x === 0))) return false;
  // 老鼠不能直接进兽穴，需先踩陷阱
  if (piece.type === 'RAT' && dest.terrain === 'DEN' && !piece.hasEnteredTrap) return false;
  // 河流规则
  if (dest.terrain === 'RIVER' && piece.type !== 'RAT') return false;
  if (board[from.x][from.y].terrain === 'RIVER' && piece.type === 'RAT' && dest.terrain !== 'RIVER') {
    if (dest.piece && dest.piece.type === 'ELEPHANT') return false;
  }
  // 吃子规则
  if (dest.piece) {
    if (!canCapture(board, from, to)) return false;
  }
  return true;
}

function isJumpRiver(board, from, to) {
  // 横纵直线跳跃，且中间全是河
  if (from.x === to.x && Math.abs(from.y - to.y) > 1) {
    const minY = Math.min(from.y, to.y), maxY = Math.max(from.y, to.y);
    for (let y = minY + 1; y < maxY; y++) {
      if (board[from.x][y].terrain !== 'RIVER') return false;
    }
    return true;
  }
  if (from.y === to.y && Math.abs(from.x - to.x) > 1) {
    const minX = Math.min(from.x, to.x), maxX = Math.max(from.x, to.x);
    for (let x = minX + 1; x < maxX; x++) {
      if (board[x][from.y].terrain !== 'RIVER') return false;
    }
    return true;
  }
  return false;
}

function canJumpRiver(board, from, to) {
  // 跳跃路径上不能有老鼠
  if (from.x === to.x) {
    const minY = Math.min(from.y, to.y), maxY = Math.max(from.y, to.y);
    for (let y = minY + 1; y < maxY; y++) {
      if (board[from.x][y].piece && board[from.x][y].piece.type === 'RAT') return false;
    }
  } else if (from.y === to.y) {
    const minX = Math.min(from.x, to.x), maxX = Math.max(from.x, to.x);
    for (let x = minX + 1; x < maxX; x++) {
      if (board[x][from.y].piece && board[x][from.y].piece.type === 'RAT') return false;
    }
  }
  return true;
}

function getTrapOwner(x, y) {
  if ((x === 0 && (y === 2 || y === 4)) || (x === 1 && y === 3)) return 1;
  if ((x === 8 && (y === 2 || y === 4)) || (x === 7 && y === 3)) return 0;
  return null;
}

function getPieceRank(board, x, y) {
  const piece = board[x][y].piece;
  if (!piece) return 0;
  if (board[x][y].terrain === 'TRAP') return 0;
  return pieceRank[piece.type];
}

function canCapture(board, from, to) {
  const attacker = board[from.x][from.y].piece;
  const defender = board[to.x][to.y].piece;
  const dest = board[to.x][to.y].terrain;
  // 陷阱内可被任何动物吃
  if (dest === 'TRAP') return true;
  // 鼠吃象
  if (attacker.type === 'RAT' && defender.type === 'ELEPHANT') {
    if (board[from.x][from.y].terrain === 'RIVER') return false;
    return true;
  }
  // 象不能吃鼠
  if (attacker.type === 'ELEPHANT' && defender.type === 'RAT') {
    return false;
  }
  // 同等级互吃同归于尽
  if (pieceRank[attacker.type] === pieceRank[defender.type]) return true;
  // 普通吃子
  return getPieceRank(board, from.x, from.y) >= getPieceRank(board, to.x, to.y);
}

export function checkWinner(board) {
  // 兽穴胜利
  if (board[0][3].piece && board[0][3].piece.owner === 0) return 0;
  if (board[8][3].piece && board[8][3].piece.owner === 1) return 1;
  // 全灭胜利
  let p0 = false, p1 = false;
  for (let i = 0; i < ROWS; i++) for (let j = 0; j < COLS; j++) {
    const p = board[i][j].piece;
    if (p) {
      if (p.owner === 0) p0 = true;
      if (p.owner === 1) p1 = true;
    }
  }
  if (!p0) return 1;
  if (!p1) return 0;
  return null;
}

// 棋子不能回头/三次循环判和等高级规则可后续补充 